package services

import (
	"GOPAAS/internal/app/model"
	"GOPAAS/internal/utils"
	"errors"
	"time"
)

type PraiseService struct {
}

func GetPraiseService() *PraiseService {
	return &PraiseService{}
}

// AddOncePraise 对象只能点赞一次
func AddOncePraise(user_id int64, res_model string, res_id int64, state bool) (err error) {
	db = getDB()
	var praise model.ResPraise
	db.Where("user_id=? and res_model=? and res_id=?", user_id, res_model, res_id).First(&praise)
	if state {
		//点赞
		if praise.Id > 0 {
			err = errors.New("你已经点过赞了")
			return
		}
		var user model.ResUsers
		db.Preload("Partner").First(&user, user_id)
		err = db.Create(&model.ResPraise{
			UserId:     user_id,
			Name:       user.Partner.Name,
			ResModel:   res_model,
			ResId:      res_id,
			CreateDate: time.Now(),
		}).Error
	} else {
		//取消点赞
		if praise.Id > 0 {
			err = db.Delete(&praise).Error
		}
	}
	return
}

// AddOnceDayPraise 对象每天只能点赞一次
func AddOnceDayPraise(user_id int64, res_model string, res_id int64) (err error) {
	db = getDB()
	var praise model.ResPraise
	start_date := utils.GetTodayZero(time.Now())
	end_date := utils.GetTodayZero(time.Now().AddDate(0, 0, 1))
	db.Where("user_id=? and res_model=? and res_id=? and create_date between ?,?", user_id, res_model, res_id, start_date, end_date).First(&praise)
	if praise.Id > 0 {
		err = errors.New("你今天已经点过赞了")
		return
	}
	var user model.ResUsers
	db.Preload("Partner").First(&user, user_id)
	err = db.Create(&model.ResPraise{
		UserId:     user_id,
		Name:       user.Partner.Name,
		ResModel:   res_model,
		ResId:      res_id,
		CreateDate: time.Now(),
	}).Error
	return
}

// AddFollow 关注（取消）
func AddFollow(user_id int64, res_model string, res_id int64, state bool) (err error) {
	db = getDB()
	var user model.ResUsers
	db.Preload("Partner").First(&user, user_id)
	var follow model.MailFollowers
	db.Where("partner_id=? and res_model=? and res_id=?", user.PartnerId, res_model, res_id).First(&follow)
	if state {
		//点赞
		if follow.Id > 0 {
			err = errors.New("你已经关注了")
			return
		}
		err = db.Create(&model.MailFollowers{
			PartnerId: user.PartnerId,
			ResModel:  res_model,
			ResId:     res_id,
		}).Error
	} else {
		//取消点赞
		if follow.Id > 0 {
			err = db.Delete(&follow).Error
		}
	}
	return
}
